package com.sljy.hzk.ui;

import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.CheckBox;
import android.widget.ImageButton;
import android.widget.ImageView;

import com.bumptech.glide.Glide;
import com.sljy.hzk.MainActivity;
import com.sljy.hzk.R;
import com.sljy.hzk.animation.AnimationManager;
import com.sljy.hzk.annotation.ActivityInfo;
import com.sljy.hzk.base.BaseActivity;
import com.sljy.hzk.base.UserInfo;
import com.sljy.hzk.entity.UserEntity;
import com.sljy.hzk.net.BaseCallBack;
import com.sljy.hzk.net.HttpHeper;
import com.sljy.hzk.net.service.UserServive;
import com.sljy.hzk.room.AppDataBase;
import com.sljy.hzk.room.dao.UserDao;
import com.sljy.hzk.util.NetWorkUtils;
import com.sljy.hzk.view.CircleImageView;
import com.sljy.hzk.view.LineEditText;
import com.sljy.hzk.view.adapter.LoginItemMyAdapter;
import com.trello.rxlifecycle2.android.ActivityEvent;

import java.util.List;

import butterknife.BindView;

@ActivityInfo(layout = R.layout.activity_login, isFullscreen = true)
public class LoginActivity extends BaseActivity {
    @BindView(R.id.et_user)
    LineEditText etName;
    @BindView(R.id.et_psw)
    LineEditText etPassword;
    @BindView(R.id.fastLogin)
    CheckBox checkBox;
    @BindView(R.id.loginBtn)
    ImageButton loginBtn;
    @BindView(R.id.defaule_head)
    CircleImageView defaule_head;
    UserDao userDao;
    private boolean IsLogin = true;
    //private ArrayAdapter<String> adapter;
    private LoginItemMyAdapter adapter;
    @Override
    protected void init() {
        userDao = AppDataBase.getInstance().getUserDao();
       if (userDao.getPermanentUser() != null){
           UserInfo.setUserInfo(userDao.getPermanentUser());
           startActivity(MainActivity.class);
           finish();
       }
        loginBtn.setOnTouchListener(new View.OnTouchListener(){
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch (event.getAction()){
                    case MotionEvent.ACTION_DOWN:
                        AnimationManager.Instance().DoScaleAction(v, 1.0f,1.05f,1.0f,1.05f, 50);
                        break;
                    case  MotionEvent.ACTION_UP:
                        AnimationManager.Instance().DoScaleAction(v, 1.05f,1.0f,1.05f,1.0f,50);
                        login();
                        break;
                }
                return false;
            }
        });

        adapter = new LoginItemMyAdapter(readOldUserList(),LoginActivity.this);
        etName.setAdapter(adapter,this);
        etName.setIsDefaultRight(true);
        etName.addTextChangedListener(new TextWatcher(){

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                Log.i("beforeTextChanged",s.toString());
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                Log.i("onTextChanged",s.toString());
            }

            @Override
            public void afterTextChanged(Editable s) {
                Log.i("afterTextChanged",s.toString());
            }
        });
    }

  //  @OnClick(R.id.loginBtn)
  void login(){
        if(!NetState()){
            return;
        }
        if(!IsLogin)return;
        String accounts = etName.getText().toString();
        if (TextUtils.isEmpty(accounts)){
            showToast("用户名为空");
            return;
        }
        String password = etPassword.getText().toString();
        if (TextUtils.isEmpty(password)){
            showToast("密码为空");
            return;
        }
        IsLogin = false;
        HttpHeper.get().create(UserServive.class)
                .userLogin(accounts,password)
                .compose(this.bindUntilEvent(ActivityEvent.DESTROY))
                .compose(getThread())
                .subscribe(new BaseCallBack<UserEntity>(this,"登陆中"){
                    @Override
                    public void onCallBackSuccess(UserEntity data) {
                        data.setMenuStr(data.getMenu().toString());
                        data.setAccounts(etName.getText().toString());
                        data.setPassword(etPassword.getText().toString());
                        UserInfo.setUserInfo(data);
                        if(checkBox.isChecked()){
                            //是否存在，存在就进行更新
                            UserEntity u = userDao.getUserFacc(etName.getText().toString());
                            data.setIsPermanent(1);
                            if(u == null)
                                userDao.insert(data);
                            else{
                                u.setPassword(data.getPassword());
                                userDao.Update(u);
                            }
                        }
                        startActivity(MainActivity.class);
                        IsLogin = true;
                        finish();
                    }
                    @Override
                    public void onFail(String mes) {
                        IsLogin = true;
                        showToast(mes);
                    }
                });
    }

    /**
     * 帐号下拉打开
     * */
    public void hide(int state){
        etPassword.setVisibility(state);
        checkBox.setVisibility(state);
        loginBtn.setVisibility(state);
    }

    /**
     * 获取历史本地用户信息列表
     * */
    private List<UserEntity> readOldUserList(){
        List<UserEntity> list = userDao.getUser();
        //TODO 获取本地历史用户数据，并检查网络获取头像
        return list;
    }

    /**
     * 设置密码
     * */
    public void setPasswordEdittext(String psw){
        etPassword.setText(psw);
    }

    /**
     * 显示用户头像
     * */
    public void setUserDefaultHead(String pic){
        if(!NetWorkUtils.isNetworkConnected(this))
            return;
        if(!pic.equals("")){
            defaule_head.setVisibility(View.VISIBLE);
            String imgPath = pic.replace("\\","/");
            Glide.with(this).load(imgPath).into(defaule_head);
        }
    }
}
